<?php

/**
 * Description of biz
 *
 * @author Nazmul
 */
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

// ## paublic page show only html page
// ## no extra method use other then index method
class User extends CI_Controller {

    var $headerInfo = array();

    public function __construct() {
        parent::__construct();
        $this->headerInfo = $this->headerInfo = $this->pageinfo->getHeaderInfo();
    }

    // this is check login varifiction
    public function _remap($method, $params = array()) {
        if ($this->userauth->isLoggedIn()) { // check login then run below method and code otherwish not
            if ($method === 'administrator') {
                redirect(base_url() . 'admin');
            } else if (method_exists($this, $method)) { // if exist then ok 
                $this->$method(); // call your needed method
            } else { // if not show page not found error message
                show_404();
            }
        } else { // if user not login then set show this error message
            $this->administrator();
        }
    }

    // forgotpassword :: forgot password hendlear
    public function forgotpassword() {
        $getForgotPasswordKey = $this->uri->segment(3);
        if (empty($getForgotPasswordKey)) {
            show_error("The request cannot be fulfilled due to bad syntax", 400, "Bad Request");
        } else {
            // init userdata var and decode verify key and set to userdata
            $userdata = array();
            // decode forgot key
            $forgotPasswordKeyData = $this->encrypt->decode($getForgotPasswordKey, md5("forgotpassword"));
            if (!empty($forgotPasswordKeyData)) {
                $expData = explode("::", $forgotPasswordKeyData);
                if (!empty($expData) && isset($expData[1]) && !empty($expData[1])) {
                    // data set to userdata array
                    list($userdata['datetime'], $userdata['userid'], $userdata['email'], $userdata['user_type']) = $expData;
                    // check and varify request
                    $data = $this->usermodel->getUserForgotExpireDT($userdata);
                    $dataforgotdt = $data['forgot_password_expire_datetime'];
                    if (!empty($data) && (int) trim($userdata['datetime']) <= (int) $dataforgotdt) {
                        // set user data for update user data
                        $this->session->set_userdata('forgot_userid', $userdata['userid']);
                        $this->session->set_userdata('forgot_email', $userdata['email']);
                        // parser or view page call
                        $this->parser->parse('public_page/forgotpassword', $userdata);
                    } else {
                        $data = array("pagetitle" => "Expaire your token");
                        $data['pagetitle'] = "Token Expire";
                        $data['pagemessage'] = "Expire your token";
                        $this->parser->parse('public_page/pageerror', $data);
                    }
                } else {
                    // if not valid then set it
                    $data['pagetitle'] = "Request Problem";
                    $data['pagemessage'] = "The request cannot be fulfilled due to bad syntax";
                    $this->parser->parse('public_page/pageerror', $data);
                }
            } else {
                // if not valid then set it
                $data['pagetitle'] = "Request Problem";
                $data['pagemessage'] = "The request cannot be fulfilled due to bad syntax";
                $this->parser->parse('public_page/pageerror', $data);
            }
        }
    }

    // biz owner forgot password
    public function userforgotpassword() {
        // init result array
        $result = array();
        $result['message'] = "";
        $result['success'] = false;
        if (true && $this->input->post()) {
            //check validation
            $this->form_validation->set_rules('newpass', 'New Password', 'required');
            $this->form_validation->set_rules('renewpass', 'Retype New Password', 'required|matches[newpass]');
            //## validation
            if ($this->form_validation->run() === TRUE) { // is form validation ok then 
                $newpass = md5($this->input->post('renewpass'));
                $userinfo['userid'] = $this->session->userdata('forgot_userid');
                $userinfo['email'] = $this->session->userdata('forgot_email');
                // save db
                $isSuccess = $this->usermodel->updatePasswordByUserInfo($newpass, $userinfo);
                if ($isSuccess) {
                    $result['message'] = "Successfully changed password.";
                    $result['success'] = true;
                }
            } else {
                // set error message from validation
                $result['message'] = validation_errors();
            }
        }
        // add/update result return or print
        print json_encode($result);
    }

    public function administrator() {
        if ($this->input->get()) {
            
        } else if ($this->input->post()) {
            $result = array();
            $result['message'] = validation_errors("<span>", "</span>");
            $result['success'] = false;
            //check validation
            $this->form_validation->set_rules('email', 'Email', 'required|valid_email|trim');
            $this->form_validation->set_rules('password', 'Password', 'required|trim');
            //## validation
            if ($this->form_validation->run() === TRUE) { // is form validation ok then 
                $email = $this->input->post('email');
                $password = md5($this->input->post('password'));
                // check login
                $userid = $this->usermodel->userLogin($email, $password);
                if ($userid > 0) {
                    $userDetails = $this->usermodel->getUserInfo($userid);
                    if (!empty($userDetails)) {
                        $this->userauth->setUserInfo($userDetails, 'admin');
                        $result['message'] = "Successfully changed password.";
                        $result['success'] = true;
                    }
                }
            } else {
                // set error message from validation
                $result['message'] = validation_errors("<span>", "</span>");
                $result['success'] = false;
            }
            echo json_encode($result);
        } else {
            $this->load->view('admin/login');
        }
    }

    // user logout method then call rpauth and setUserLogOut method 
    // then clear his/her session data
    public function logout() {
        // call to rpauth lib and setLogOut method
        $this->userauth->setUserLogOut();
        // when session clear then goto home page
        redirect(base_url());
    }

    // this is index for public html page 
    public function index() {
        if ($this->userauth->getUserRole() === 'admin') {
            $data = $this->headerInfo['dashboard'];
            $this->load->view('admin/dashboard', $data);
        } else {
            $this->administrator();
        }
    }

    private function getHeaderInfo() {
        // this is common meta description and keys
        $commonmd = "Your description";
        $commonmk = "Your keywords";

        // header array page name and array index should be same
        $headerInfo = array(
            "login" => array(
                "pagetitle" => "Login",
                "metadescription" => $commonmd,
                "metakeywords" => $commonmk
            )
        );
        return $headerInfo;
    }

    ////////////////########################//////////////////////////
    ////////////////########################//////////////////////////
    ////////////// This Section need user auth ///////////////////////
    ////////////////########################//////////////////////////
    ////////////////#######################///////////////////////////
    // change password html page
    public function changepassword() {
        if ($this->input->post('gethtml') === "true") {
            $this->load->view('common/changepassword');
        }
    }

    // biz owner change password
    public function change_password() {
        // init result array
        $result = array();
        $result['message'] = "";
        $result['success'] = false;
        if (true && $this->input->post()) {
            //check validation
            $this->form_validation->set_rules('currentpass', 'Current Password', 'required');
            $this->form_validation->set_rules('newpass', 'New Password', 'required');
            $this->form_validation->set_rules('renewpass', 'Retype New Password', 'required|matches[newpass]');
            //## validation
            if ($this->form_validation->run() === TRUE) { // is form validation ok then 
                $currentpass = md5($this->input->post('currentpass'));
                $newpass = md5($this->input->post('renewpass'));
                // save db
                $isSuccess = $this->usermodel->updatePassword($newpass, $currentpass);
                if ($isSuccess) {
                    $result['message'] = "Successfully changed password.";
                    $result['success'] = true;
                } else {
                    $result['message'] = "Current password does not match";
                }
            } else {
                // set error message from validation
                $result['message'] = validation_errors();
            }
        }
        // add/update result return or print
        print json_encode($result);
    }

}

/* End of file publicpage.php */
/* Location: ./application/controllers/publicpage.php */